import distributedKVStore from '@ohos.data.distributedKVStore';

export class SyncService {
  private store?: any;
  private kvManager?: any;

  /**
   * 初始化分布式 KVStore。
   * @param params { context?: any; bundleName: string; storeId: string }
   *  - context：UIAbility 上下文，推荐传入（不同 API 版本可能必需）
   *  - bundleName：应用包名
   *  - storeId：KVStore 的标识
   */
  async init(params: { context?: any; bundleName: string; storeId: string }): Promise<void> {
    const { context, bundleName, storeId } = params;
    try {
      const kvManagerConfig: any = { bundleName };
      if (context) {
        kvManagerConfig.context = context;
      }
      // 兼容某些版本需要 userId 的情况
      if (kvManagerConfig.userId === undefined) {
        kvManagerConfig.userId = '0';
      }

      this.kvManager = distributedKVStore.createKVManager(kvManagerConfig);

      const options: any = {
        createIfMissing: true,
        encrypt: false,
        autoSync: true,
        kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
        securityLevel: distributedKVStore.SecurityLevel.S2
      };

      await new Promise<void>((resolve, reject) => {
        this.kvManager!.getKVStore(storeId, options, (err, store) => {
          if (err && (err as any).code) {
            console.warn('getKVStore error', JSON.stringify(err));
            reject(err);
            return;
          }
          this.store = store;
          resolve();
        });
      });
    } catch (e) {
      console.warn('KVStore init failed', JSON.stringify(e));
    }
  }

  async put(key: string, value: object | string): Promise<void> {
    if (!this.store) {
      return;
    }
    const v = typeof value === 'string' ? value : JSON.stringify(value);
    await new Promise<void>((resolve, reject) => {
      this.store!.put(key, v, (err) => {
        if (err && (err as any).code) {
          reject(err);
        } else {
          resolve();
        }
      });
    });
  }

  async get(key: string): Promise<string | undefined> {
    if (!this.store) {
      return undefined;
    }
    return await new Promise<string | undefined>((resolve) => {
      this.store!.get(key, (err, val) => {
        if (err && (err as any).code) {
          resolve(undefined);
        } else {
          resolve(val as unknown as string);
        }
      });
    });
  }
}

export const syncService = new SyncService();